# gui/widgets/control_widgets.py
"""
控制面板和测量结果显示组件
"""

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import numpy as np


class MeasurementDisplayWidget(QWidget):
    """测量结果显示组件"""

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setObjectName("MeasurementDisplayWidget")
        self.init_ui()

        # 加载样式
        from gui.styles.style_manager import style_manager
        self.setStyleSheet(style_manager.get_style("widgets"))

    def init_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)

        # 标题
        title_label = QLabel("测量结果")
        title_label.setObjectName("MeasurementTitle")
        layout.addWidget(title_label)

        # 测量结果表格
        self.table = QTableWidget()
        self.table.setObjectName("MeasurementTable")
        self.table.setColumnCount(7)
        self.table.setHorizontalHeaderLabels([
            "目标ID", "距离(km)", "方位角(°)", "俯仰角(°)", "速度(m/s)", "SNR(dB)", "RCS(m²)"
        ])

        # 设置表格样式 - 暗色主题优化
        self.table.horizontalHeader().setStretchLastSection(True)
        self.table.setAlternatingRowColors(False)  # 禁用交替行颜色，使用自定义暗色主题
        self.table.setSelectionBehavior(QAbstractItemView.SelectRows)

        # 应用暗色主题样式
        self.apply_dark_table_style()

        layout.addWidget(self.table)

        # 统计信息
        self.stats_label = QLabel("统计信息: 检测目标数: 0")
        layout.addWidget(self.stats_label)

    def apply_dark_table_style(self):
        """应用暗色主题表格样式"""
        dark_table_style = """
            QTableWidget {
                background-color: #0d1117;
                border: 2px solid #30363d;
                border-radius: 8px;
                color: #f0f6fc;
                selection-background-color: #1f6feb;
                selection-color: #ffffff;
                gridline-color: #21262d;
                font-size: 11px;
            }

            QTableWidget::item {
                padding: 8px;
                border-bottom: 1px solid #21262d;
                background-color: #0d1117;
            }

            QTableWidget::item:hover {
                background-color: #161b22;
            }

            QTableWidget::item:selected {
                background-color: #1f6feb;
                color: #ffffff;
            }

            QHeaderView::section {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #21262d, stop:1 #161b22);
                border: 1px solid #30363d;
                color: #58a6ff;
                font-weight: 600;
                padding: 8px;
                font-size: 12px;
            }

            QHeaderView::section:hover {
                background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
                    stop:0 #1f6feb, stop:1 #0969da);
                color: #ffffff;
            }
        """
        self.table.setStyleSheet(dark_table_style)

    def update_measurements(self, measurements, targets_info=None):
        """更新测量结果

        Args:
            measurements: 测量结果列表（包含雷达测量值）
            targets_info: 目标信息，可以是Target对象列表或字典列表（用于获取RCS）
        """
        self.table.setRowCount(len(measurements))

        for i, meas in enumerate(measurements):
            # 目标ID（简化处理）
            target_id = f"T{i+1}"
            self.table.setItem(i, 0, QTableWidgetItem(target_id))

            # 距离 - 从米转换为千米显示
            range_m = meas['range']  # 内部单位：米
            range_km = range_m / 1000  # 转换为千米显示
            self.table.setItem(i, 1, QTableWidgetItem(f"{range_km:.2f}"))

            # 方位角 - 使用雷达测量值（单脉冲测角结果）
            azimuth_measured = meas.get('azimuth_error', 0.0)  # 单脉冲测角的方位角测量值
            self.table.setItem(i, 2, QTableWidgetItem(f"{azimuth_measured:.2f}"))

            # 俯仰角 - 使用雷达测量值（单脉冲测角结果）
            elevation_measured = meas.get('elevation_error', 0.0)  # 单脉冲测角的俯仰角测量值
            self.table.setItem(i, 3, QTableWidgetItem(f"{elevation_measured:.2f}"))

            # 速度
            self.table.setItem(i, 4, QTableWidgetItem(f"{meas['velocity']:.2f}"))

            # SNR
            self.table.setItem(i, 5, QTableWidgetItem(f"{meas['snr']:.1f}"))

            # RCS（从目标信息获取）
            rcs = 1.0
            if targets_info and i < len(targets_info):
                target = targets_info[i]
                # 处理字典或对象两种格式
                if isinstance(target, dict):
                    rcs = target.get('rcs', 1.0)
                else:
                    rcs = target.rcs
            self.table.setItem(i, 6, QTableWidgetItem(f"{rcs:.2f}"))

        # 更新统计信息
        self.stats_label.setText(f"统计信息: 检测目标数: {len(measurements)}")


class ControlPanelWidget(QWidget):
    """控制面板组件"""

    # 信号定义
    simulation_started = pyqtSignal()
    simulation_stopped = pyqtSignal()
    simulation_paused = pyqtSignal()  # 新增：暂停信号
    simulation_resumed = pyqtSignal()  # 新增：恢复信号
    simulation_reset = pyqtSignal()
    target_added = pyqtSignal(dict)
    parameter_changed = pyqtSignal(str, float)
    demo_requested = pyqtSignal()
    clear_targets_requested = pyqtSignal()

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setObjectName("ControlPanelWidget")
        self.init_ui()

        # 加载样式
        from gui.styles.style_manager import style_manager
        self.setStyleSheet(style_manager.get_style("widgets"))

    def init_ui(self):
        """初始化UI"""
        layout = QVBoxLayout(self)

        # 仿真控制组 - 改为网格布局
        sim_group = QGroupBox("仿真控制")
        sim_group.setObjectName("ControlGroupBox")
        sim_layout = QGridLayout(sim_group)

        self.start_btn = QPushButton("开始仿真")
        self.start_btn.setObjectName("ControlPanelButton")
        self.pause_btn = QPushButton("暂停")  # 新增：暂停按钮
        self.pause_btn.setObjectName("ControlPanelButton")
        self.pause_btn.setEnabled(False)  # 初始禁用
        self.stop_btn = QPushButton("停止仿真")
        self.stop_btn.setObjectName("ControlPanelButton")
        self.reset_btn = QPushButton("重置仿真")
        self.reset_btn.setObjectName("ControlPanelButton")

        # 添加仿真时长输入框
        self.simulation_duration_spinbox = QDoubleSpinBox()
        self.simulation_duration_spinbox.setObjectName("ControlPanelSpinBox")
        self.simulation_duration_spinbox.setRange(0.1, 3600.0)  # 0.1秒到1小时
        self.simulation_duration_spinbox.setValue(10.0)  # 默认10秒
        self.simulation_duration_spinbox.setSuffix(" 秒")
        self.simulation_duration_spinbox.setDecimals(1)
        self.simulation_duration_spinbox.setToolTip("设置连续仿真持续时间（秒）")

        # 使用网格布局排列按钮 - 2x3布局
        sim_layout.addWidget(self.start_btn, 0, 0)
        sim_layout.addWidget(self.pause_btn, 0, 1)  # 新增：暂停按钮位置
        sim_layout.addWidget(self.stop_btn, 0, 2)
        sim_layout.addWidget(self.reset_btn, 1, 0)
        sim_layout.addWidget(QLabel("仿真时长:"), 1, 1)
        sim_layout.addWidget(self.simulation_duration_spinbox, 1, 2)

        layout.addWidget(sim_group)

        # 目标管理组 - 恢复原始表单布局
        target_group = QGroupBox("目标管理")
        target_group.setObjectName("ControlGroupBox")
        target_layout = QFormLayout(target_group)

        self.target_x = QDoubleSpinBox()
        self.target_x.setObjectName("ControlPanelSpinBox")
        self.target_y = QDoubleSpinBox()
        self.target_y.setObjectName("ControlPanelSpinBox")
        self.target_z = QDoubleSpinBox()
        self.target_z.setObjectName("ControlPanelSpinBox")
        self.target_vx = QDoubleSpinBox()
        self.target_vx.setObjectName("ControlPanelSpinBox")
        self.target_vy = QDoubleSpinBox()
        self.target_vy.setObjectName("ControlPanelSpinBox")
        self.target_vz = QDoubleSpinBox()
        self.target_vz.setObjectName("ControlPanelSpinBox")
        self.target_rcs = QDoubleSpinBox()
        self.target_rcs.setObjectName("ControlPanelSpinBox")

        # 设置范围和默认值
        for spinbox in [self.target_x, self.target_y, self.target_z]:
            spinbox.setRange(-999999, 999999)  # 移除最大值限制
            spinbox.setSuffix(" km")
        for spinbox in [self.target_vx, self.target_vy, self.target_vz]:
            spinbox.setRange(-999999, 999999)  # 移除最大值限制
            spinbox.setSuffix(" m/s")
            spinbox.setDecimals(2)  # 速度精确到小数点后2位

        # 设置推荐的默认目标参数（无距离/速度模糊）
        # 参考: docs/recommended_scenarios.md
        self.target_x.setValue(50.0)   # 50 km（在安全范围内）
        self.target_y.setValue(3.0)    # 3 km
        self.target_z.setValue(0.0)    # 0 km高度
        self.target_vx.setValue(5.0)   # 5 m/s
        self.target_vy.setValue(2.0)   # 2 m/s
        self.target_vz.setValue(0.0)   # 0 m/s

        self.target_rcs.setRange(0.1, 100.0)
        self.target_rcs.setValue(10.0)  # 10 m²（良好的RCS）
        self.target_rcs.setSuffix(" m²")

        # 使用表单布局排列目标参数
        target_layout.addRow("X坐标(km):", self.target_x)
        target_layout.addRow("Y坐标(km):", self.target_y)
        target_layout.addRow("Z坐标(km):", self.target_z)
        target_layout.addRow("X速度(m/s):", self.target_vx)
        target_layout.addRow("Y速度(m/s):", self.target_vy)
        target_layout.addRow("Z速度(m/s):", self.target_vz)
        target_layout.addRow("RCS(m²):", self.target_rcs)

        # 目标操作按钮
        target_btn_layout = QHBoxLayout()

        self.add_target_btn = QPushButton("添加目标")
        self.add_target_btn.setObjectName("ControlPanelButton")

        self.demo_btn = QPushButton("🎯 添加默认目标")
        self.demo_btn.setObjectName("ControlPanelButton")
        self.demo_btn.setToolTip("添加默认的飞机目标")

        self.clear_btn = QPushButton("🧹 清空所有目标")
        self.clear_btn.setObjectName("ControlPanelButton")
        self.clear_btn.setToolTip("清空所有目标")

        target_btn_layout.addWidget(self.add_target_btn)
        target_btn_layout.addWidget(self.demo_btn)
        target_btn_layout.addWidget(self.clear_btn)

        target_layout.addRow(target_btn_layout)

        layout.addWidget(target_group)

        # 雷达参数组 - 恢复原始表单布局
        radar_group = QGroupBox("雷达参数")
        radar_group.setObjectName("ControlGroupBox")
        radar_layout = QFormLayout(radar_group)

        self.frequency_spin = QDoubleSpinBox()
        self.frequency_spin.setObjectName("ControlPanelSpinBox")
        self.frequency_spin.setRange(1.0, 50.0)
        self.frequency_spin.setValue(10.0)  # 10 GHz（X波段）
        self.frequency_spin.setSuffix(" GHz")
        self.frequency_spin.setDecimals(1)

        self.power_spin = QDoubleSpinBox()
        self.power_spin.setObjectName("ControlPanelSpinBox")
        self.power_spin.setRange(0, 10000)  # 最小值改为0
        self.power_spin.setValue(1500)  # 1500 W（优化后的功率）
        self.power_spin.setSuffix(" W")
        self.power_spin.setDecimals(0)

        self.sampling_rate_spin = QDoubleSpinBox()
        self.sampling_rate_spin.setObjectName("ControlPanelSpinBox")
        self.sampling_rate_spin.setRange(10, 500)  # 10MHz到500MHz
        self.sampling_rate_spin.setValue(100)  # 默认100MHz
        self.sampling_rate_spin.setSuffix(" MHz")
        self.sampling_rate_spin.setDecimals(1)

        self.pulse_width_spin = QDoubleSpinBox()
        self.pulse_width_spin.setObjectName("ControlPanelSpinBox")
        self.pulse_width_spin.setRange(0.1, 100)  # 0.1到100微秒
        self.pulse_width_spin.setValue(10.0)  # 默认10微秒
        self.pulse_width_spin.setSuffix(" μs")
        self.pulse_width_spin.setDecimals(1)

        self.prt_spin = QDoubleSpinBox()
        self.prt_spin.setObjectName("ControlPanelSpinBox")
        self.prt_spin.setRange(0.1, 10)  # 0.1到10毫秒
        self.prt_spin.setValue(1.0)  # 默认1毫秒
        self.prt_spin.setSuffix(" ms")
        self.prt_spin.setDecimals(1)

        self.bandwidth_spin = QDoubleSpinBox()
        self.bandwidth_spin.setObjectName("ControlPanelSpinBox")
        self.bandwidth_spin.setRange(1, 100)  # 1到100MHz
        self.bandwidth_spin.setValue(10.0)  # 默认10MHz
        self.bandwidth_spin.setSuffix(" MHz")
        self.bandwidth_spin.setDecimals(1)

        # 距离波门参数
        self.range_gate_start_spin = QDoubleSpinBox()
        self.range_gate_start_spin.setObjectName("ControlPanelSpinBox")
        self.range_gate_start_spin.setRange(0, 500)  # 0到500km
        self.range_gate_start_spin.setValue(5.0)  # 默认5km
        self.range_gate_start_spin.setSuffix(" km")
        self.range_gate_start_spin.setDecimals(1)

        self.range_gate_width_spin = QDoubleSpinBox()
        self.range_gate_width_spin.setObjectName("ControlPanelSpinBox")
        self.range_gate_width_spin.setRange(1, 200)  # 1到200km
        self.range_gate_width_spin.setValue(100.0)  # 默认100km
        self.range_gate_width_spin.setSuffix(" km")
        self.range_gate_width_spin.setDecimals(1)

        # 接收机增益参数
        self.receiver_gain_spin = QDoubleSpinBox()
        self.receiver_gain_spin.setObjectName("ControlPanelSpinBox")
        self.receiver_gain_spin.setRange(0.0, 100.0)  # 增益范围：0-100 dB
        self.receiver_gain_spin.setValue(10.0)  # 默认10dB
        self.receiver_gain_spin.setSuffix(" dB")
        self.receiver_gain_spin.setDecimals(1)
        self.receiver_gain_spin.setToolTip("接收机增益 (LNA Gain)\n典型值：10-40dB\n放大微弱回波信号")

        # 接收机噪声系数参数
        self.receiver_noise_spin = QDoubleSpinBox()
        self.receiver_noise_spin.setObjectName("ControlPanelSpinBox")
        self.receiver_noise_spin.setRange(0.0, 100.0)  # 噪声系数范围：0-100 dB
        self.receiver_noise_spin.setValue(8.0)  # 默认8dB
        self.receiver_noise_spin.setSuffix(" dB")
        self.receiver_noise_spin.setDecimals(1)
        self.receiver_noise_spin.setToolTip("接收机噪声系数 (Noise Figure)\n典型值：3-10dB\n越小表示接收机性能越好")

        # 使用表单布局排列雷达参数
        radar_layout.addRow("频率:", self.frequency_spin)
        radar_layout.addRow("功率:", self.power_spin)
        radar_layout.addRow("采样率:", self.sampling_rate_spin)
        radar_layout.addRow("脉宽:", self.pulse_width_spin)
        radar_layout.addRow("PRT:", self.prt_spin)
        radar_layout.addRow("带宽:", self.bandwidth_spin)
        radar_layout.addRow("接收机增益:", self.receiver_gain_spin)
        radar_layout.addRow("噪声系数:", self.receiver_noise_spin)
        radar_layout.addRow("波门起始:", self.range_gate_start_spin)
        radar_layout.addRow("波门宽度:", self.range_gate_width_spin)

        layout.addWidget(radar_group)

        # 连接信号
        self.connect_signals()

    def connect_signals(self):
        """连接信号和槽"""
        self.start_btn.clicked.connect(self.simulation_started.emit)
        self.pause_btn.clicked.connect(self.on_pause_clicked)  # 新增：暂停/恢复按钮
        self.stop_btn.clicked.connect(self.simulation_stopped.emit)
        self.reset_btn.clicked.connect(self.simulation_reset.emit)

        self.add_target_btn.clicked.connect(self.add_target)

        self.frequency_spin.valueChanged.connect(lambda v: self.parameter_changed.emit('frequency', v))
        self.power_spin.valueChanged.connect(lambda v: self.parameter_changed.emit('power', v))
        self.sampling_rate_spin.valueChanged.connect(lambda v: self.parameter_changed.emit('sampling_rate', v))
        self.pulse_width_spin.valueChanged.connect(lambda v: self.parameter_changed.emit('pulse_width', v))
        self.prt_spin.valueChanged.connect(lambda v: self.parameter_changed.emit('pulse_repetition_time', v))
        self.bandwidth_spin.valueChanged.connect(lambda v: self.parameter_changed.emit('bandwidth', v))
        self.receiver_gain_spin.valueChanged.connect(lambda v: self.parameter_changed.emit('receiver_gain_db', v))
        self.receiver_noise_spin.valueChanged.connect(lambda v: self.parameter_changed.emit('receiver_noise_db', v))
        self.range_gate_start_spin.valueChanged.connect(lambda v: self.parameter_changed.emit('range_gate_start', v))
        self.range_gate_width_spin.valueChanged.connect(lambda v: self.parameter_changed.emit('range_gate_width', v))

        # 目标管理按钮
        self.demo_btn.clicked.connect(self.demo_requested.emit)
        self.clear_btn.clicked.connect(self.clear_targets_requested.emit)

    def on_pause_clicked(self):
        """处理暂停/恢复按钮点击"""
        if self.pause_btn.text() == "暂停":
            self.pause_btn.setText("恢复")
            self.simulation_paused.emit()
        else:
            self.pause_btn.setText("暂停")
            self.simulation_resumed.emit()

    def set_simulation_running(self, running):
        """设置仿真运行状态（更新按钮状态）"""
        self.start_btn.setEnabled(not running)
        self.pause_btn.setEnabled(running)
        self.stop_btn.setEnabled(running)
        if not running:
            self.pause_btn.setText("暂停")  # 停止时重置按钮文本

    def add_target(self):
        """添加目标"""
        target_data = {
            'x': self.target_x.value(),
            'y': self.target_y.value(),
            'z': self.target_z.value(),
            'vx': self.target_vx.value(),
            'vy': self.target_vy.value(),
            'vz': self.target_vz.value(),
            'rcs': self.target_rcs.value()
        }
        self.target_added.emit(target_data)

    def update_radar_parameter(self, param_name: str, value: float):
        """更新雷达参数控件的值"""
        try:
            if param_name == 'frequency':
                self.frequency_spin.blockSignals(True)  # 阻止信号发射，避免循环
                self.frequency_spin.setValue(value)
                self.frequency_spin.blockSignals(False)
            elif param_name == 'power':
                self.power_spin.blockSignals(True)
                self.power_spin.setValue(value)
                self.power_spin.blockSignals(False)
            elif param_name == 'sampling_rate':
                self.sampling_rate_spin.blockSignals(True)
                self.sampling_rate_spin.setValue(value)
                self.sampling_rate_spin.blockSignals(False)
            elif param_name == 'pulse_width':
                self.pulse_width_spin.blockSignals(True)
                self.pulse_width_spin.setValue(value)
                self.pulse_width_spin.blockSignals(False)
            elif param_name == 'pulse_repetition_time':
                self.prt_spin.blockSignals(True)
                self.prt_spin.setValue(value)
                self.prt_spin.blockSignals(False)
            elif param_name == 'bandwidth':
                self.bandwidth_spin.blockSignals(True)
                self.bandwidth_spin.setValue(value)
                self.bandwidth_spin.blockSignals(False)
            elif param_name == 'receiver_gain_db':
                self.receiver_gain_spin.blockSignals(True)
                self.receiver_gain_spin.setValue(value)
                self.receiver_gain_spin.blockSignals(False)
            elif param_name == 'receiver_noise_db':
                self.receiver_noise_spin.blockSignals(True)
                self.receiver_noise_spin.setValue(value)
                self.receiver_noise_spin.blockSignals(False)
            elif param_name == 'range_gate_start':
                self.range_gate_start_spin.blockSignals(True)
                self.range_gate_start_spin.setValue(value)
                self.range_gate_start_spin.blockSignals(False)
            elif param_name == 'range_gate_width':
                self.range_gate_width_spin.blockSignals(True)
                self.range_gate_width_spin.setValue(value)
                self.range_gate_width_spin.blockSignals(False)
            print(f"SUCCESS: 已更新参数控件 {param_name} = {value}")
        except Exception as e:
            print(f"ERROR: 更新参数控件失败: {e}")

    def get_radar_parameters(self):
        """获取当前雷达参数"""
        return {
            'frequency': self.frequency_spin.value(),
            'power': self.power_spin.value(),
            'sampling_rate': self.sampling_rate_spin.value(),
            'pulse_width': self.pulse_width_spin.value(),
            'pulse_repetition_time': self.prt_spin.value(),
            'bandwidth': self.bandwidth_spin.value(),
            'receiver_gain_db': self.receiver_gain_spin.value(),
            'receiver_noise_db': self.receiver_noise_spin.value(),
            'range_gate_start': self.range_gate_start_spin.value(),
            'range_gate_width': self.range_gate_width_spin.value()
        }

    def get_simulation_duration(self):
        """获取设置的仿真时长（秒）"""
        return self.simulation_duration_spinbox.value()

    def set_simulation_duration(self, duration: float):
        """设置仿真时长（秒）"""
        self.simulation_duration_spinbox.setValue(duration)
